﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace UIFrameWork
{
    public class CoroutineExecutor : MonoBehaviour
    {
        public Action DoneCallBack;

        void Start()
        {
            DontDestroyOnLoad(transform.gameObject);
        }

        public void Do(AsyncOperation asyncOperation,Action callback)
        {
            DoneCallBack = callback;
            StartCoroutine(WaitForDone(asyncOperation));
        }

        IEnumerator WaitForDone(AsyncOperation asyncCallback)
        {
            if (asyncCallback != null)
            {
                while (!asyncCallback.isDone)
                {
                    yield return 1;
                }
                if (DoneCallBack != null)
                {
                    DoneCallBack();
                }
                Destroy(this.gameObject);
                yield return 0;
            }
        }

        public void Do(IEnumerator iEnumerator,Action callback)
        {
            DoneCallBack = callback;
            StartCoroutine(WaitForDone(iEnumerator));
        }

        IEnumerator WaitForDone(IEnumerator iEnumerator)
        {
            if (iEnumerator != null)
            {
                yield return iEnumerator;
            }
            if (DoneCallBack != null)
            {
                DoneCallBack();
            }
            Destroy(this.gameObject);
        }

        public static void Create(AsyncOperation so,Action callback)
        {
            GameObject go = new GameObject("CoroutineObject");
            CoroutineExecutor coroutineExecutor = go.AddComponent<CoroutineExecutor>();
            coroutineExecutor.Do(so,callback);
        }

        public static void Create(IEnumerator iEnumerator, Action action)
        {
            GameObject go = new GameObject("corotinneObject");
            CoroutineExecutor coroutineExecutor = go.AddComponent<CoroutineExecutor>();
            coroutineExecutor.Do(iEnumerator,action);
        }
    }
}

